package com.example.demo.service.exam.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.exam.ExamPaperRelation;
import com.example.demo.exception.ExceptionUtils;
import com.example.demo.mapper.ExamPaperRelationMapper;
import com.example.demo.service.exam.ExamPaperRelationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ExamPaperRelationServiceImpl extends ServiceImpl<ExamPaperRelationMapper, ExamPaperRelation> implements ExamPaperRelationService {

    private final ExamPaperRelationMapper mapper;

    @Override
    public void deleteByPaperId(Long paperId) {
        QueryWrapper<ExamPaperRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ExamPaperRelation::getPaperId, paperId);
        mapper.delete(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertList(List<ExamPaperRelation> relations) {
        if (CollectionUtils.isEmpty(relations)) {
            return;
        }
        relations.forEach(this::checkRelationParams);
        this.saveBatch(relations);
    }

    @Override
    public void deleteByExamPaperId(Long examPaperId) {
        if (examPaperId == null) {
            throw ExceptionUtils.exception("试卷标识不能为空");
        }
        QueryWrapper<ExamPaperRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExamPaperRelation::getPaperId, examPaperId);
        mapper.delete(wrapper);
    }

    @Override
    public List<ExamPaperRelation> getRelationByPaperId(Long paperId) {
        if (paperId == null) {
            throw ExceptionUtils.exception("试卷标识不能为空");
        }
        QueryWrapper<ExamPaperRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ExamPaperRelation::getPaperId, paperId);
        return mapper.selectList(wrapper);
    }

    private void checkRelationParams(ExamPaperRelation relation) {
        if (relation.getPaperId() == null) {
            throw ExceptionUtils.exception("试卷标识不能为空");
        }
        if (relation.getQuestionId() == null) {
            throw ExceptionUtils.exception("题目标识不能为空");
        }
        if (relation.getPercentage() == null) {
            throw ExceptionUtils.exception("题目得分占比不能为空");
        }
    }

}
